#include "BlockQueue.hpp"
#include "Thread.hpp"
#include "Task.hpp"
#include <string>
#include <unistd.h>
#include <vector>
#include <ctime>

using blockqueue_t = BlockQueue<Task>;

void Consumer(blockqueue_t &bq)
{
    while(true)
    {
        //1、取出任务
        Task t;
        bq.Pop(&t);
        //2、执行任务
        t.Excute();
        cout << "Consumer data is: " << t.ResultTostring() <<endl;
    }
} 
void Productor(blockqueue_t &bq)
{
    srand(time(nullptr)^pthread_self());
    int cnt = 10;
    while(true)
    {
        sleep(1);
        //1、获取任务
        int a = rand()%10 + 1;
        usleep(1234);
        int b = rand()%10 + 1;
        Task t(a, b);
        //2、将任务放入队列
        bq.Push(t);
        cout << "Productor data is: " << t.DebugTostring() << endl;
    }
}

void StartComm(vector<yss::Thread<blockqueue_t>>* threads, int num, 
blockqueue_t& bq, yss::func_t<blockqueue_t> func)//命名空间作用域！！！
{
    for(int i=0; i<num; i++)
    {
        string name = "thread-" + to_string(i+1);
        threads->emplace_back(func, bq, name);
        threads->back().Start();
    }
}
void StartConsumer(vector<yss::Thread<blockqueue_t>>* threads, int num, blockqueue_t& bq)
{
    StartComm(threads, num, bq, Consumer);
}
void StartProductor(vector<yss::Thread<blockqueue_t>>* threads, int num, blockqueue_t& bq)
{
    StartComm(threads, num, bq, Productor);
}

void WaitAllThread(vector<yss::Thread<blockqueue_t>>& threads)
{
    for(auto& thread:threads)
    {
        thread.Join();
    }
}

int main()
{
    blockqueue_t* bq = new blockqueue_t(5);
    vector<yss::Thread<blockqueue_t>> threads;
    StartConsumer(&threads, 1, *bq);
    StartProductor(&threads, 1, *bq);
    WaitAllThread(threads);
    return 0;
} 